import 'package:dio/dio.dart';
import 'package:intl/intl.dart';
import 'package:linux_do/config/GlobalSettingConfig.dart';

import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

main() async {
  var data = await NetworkService.instance.userCardBadge('scoful');
  print(data);
}

String converDate(String iso8601Time) {
  // 初始化时区数据
  tz.initializeTimeZones();
  // 解析 ISO 8601 格式的时间字符串
  DateTime utcDateTime = DateTime.parse(iso8601Time);
  // 获取目标时区，这里以中国上海时区为例
  tz.Location shanghai = tz.getLocation('Asia/Shanghai');
  // 将 UTC 时间转换为上海时区的时间
  tz.TZDateTime shanghaiDateTime = tz.TZDateTime.from(utcDateTime, shanghai);
  // 定义目标日期格式
  DateFormat dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');
  // 格式化时间
  return dateFormat.format(shanghaiDateTime);
}

class NetworkService {
  static NetworkService instance = NetworkService();

  Future<List<TopicData>> topicList({int page = 0}) async {
    var response =
        await Dio().get('$host/latest.json?nodefinitions=true&page=$page');
    var data = response.data;
    var list = (data['users'] as List).map((e) {
      return User.fromJson(e);
    }).toList();

    Map<int, User> map = {};
    for (var user in list) {
      map[user.id] = user;
    }
    var result = (data['topic_list']['topics'] as List).map((e) {
      return TopicData.fromJson(e);
    }).toList();
    result.map((e) {
      for (var u in e.posters) {
        var user = map[u.user_id];
        var avatar = user?.avatar_template.replaceAll('{size}', '50');
        u
          ..avatar = avatar
          ..user = user;
      }
      return e;
    }).toList();
    return result;
  }

  Future<String> topicDetail({required id}) async {
    var response = await Dio().get('$host/t/topic/$id.json');
    var rawStr = response.data['post_stream']['posts'][0]['cooked'];
    return rawStr;
  }

  Future<UserCard> userCard(String username) async {
    var response = await Dio(BaseOptions(
      headers: {'cookie': cookie},
    )).get('$host/u/$username/card.json');
    var userDataMap = response.data;
    var userbadges = await userCardBadge(username);
    return UserCard.fromJson(userDataMap)..badges = userbadges;
  }

  Future<List<UserCardBadge>> userCardBadge(String username) async {
    var response = await Dio(BaseOptions(
      headers: {'cookie': cookie},
    )).get('$host/user-badges/$username.json?grouped=true');
    return (response.data['badges'] as List).map((e) {
      return UserCardBadge.fromJson(e);
    }).toList();
  }
}

class UserCard {
  UserCardUserInfo userInfo;
  List<UserCardBadge> badges;

  UserCard({required this.userInfo, required this.badges});

  factory UserCard.fromJson(Map<String, dynamic> json) {
    return UserCard(
        userInfo: UserCardUserInfo.fromJson(json['user']),
        badges: (json['badges'] as List).map((e) {
          return UserCardBadge.fromJson(e);
        }).toList());
  }
}

class UserCardBadge {
  int id;
  String name;
  int grant_count;
  String icon;
  int badge_type_id;
  String? image_url;

  UserCardBadge(
      {required this.id,
      required this.badge_type_id,
      required this.name,
      this.image_url,
      required this.grant_count,
      required this.icon});

  factory UserCardBadge.fromJson(Map<String, dynamic> json) {
    return UserCardBadge(
        id: json['id'],
        name: json['name'],
        grant_count: json['grant_count'],
        badge_type_id: json['badge_type_id'],
        image_url: json['image_url'],
        icon: json['icon']);
  }
}

class UserCardUserInfo {
  UserInfoStatus? status;
  int id;
  String username;
  String? name;
  String avatar_template;
  int? trust_level;
  bool admin;
  int time_read;
  int recent_time_read;
  String cakedate;
  String? birthdate;
  int gamification_score;
  String? card_background_upload_url;
  String? bio_excerpt;
  String? flair_url;
  String? flair_name;
  String last_posted_at;
  String? website;

  UserCardUserInfo({
    this.status,
    required this.id,
    this.website,
    required this.username,
    this.name,
    required this.avatar_template,
    this.trust_level,
    required this.admin,
    required this.time_read,
    required this.recent_time_read,
    required this.cakedate,
    this.birthdate,
    this.flair_url,
    this.flair_name,
    this.bio_excerpt,
    required this.gamification_score,
    this.card_background_upload_url,
    required this.last_posted_at,
  });

  factory UserCardUserInfo.fromJson(Map<String, dynamic> json) {
    return UserCardUserInfo(
      status: UserInfoStatus.fromJson(json['status']),
      id: json['id'],
      website: json['website'],
      last_posted_at: converDate(json['last_posted_at']),
      username: json['username'],
      bio_excerpt: json['bio_excerpt'],
      avatar_template:
          '$host${(json['avatar_template'] as String).replaceAll('{size}', '50')}',
      admin: json['admin'],
      flair_url: json['flair_url'] == null
          ? null
          : '$host${(json['flair_url'] as String).replaceAll('{size}', '50')}',
      flair_name: json['flair_name'],
      time_read: json['time_read'],
      recent_time_read: json['recent_time_read'],
      cakedate: json['cakedate'] ?? '',
      name: json['name'],
      birthdate: json['birthdate'],
      gamification_score: json['gamification_score'],
      card_background_upload_url: json['card_background_upload_url'] == null
          ? null
          : '$host${json['card_background_upload_url']}',
    );
  }
}

class UserInfoStatus {
  String? description;
  String? emoji;

  UserInfoStatus({required this.description, this.emoji});

  factory UserInfoStatus.fromJson(Map<String, dynamic>? json) {
    return UserInfoStatus(
        description: json?['description'], emoji: json?['emoji']);
  }
}

class User {
  int id;
  String avatar_template;
  String? flair_url;
  String username;

  User(
      {required this.id,
      required this.avatar_template,
      required this.flair_url,
      required this.username});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
        id: json['id'],
        avatar_template: json['avatar_template'],
        flair_url: json['flair_url'],
        username: json['username']);
  }
}

class TopicData {
  int id;
  String title;
  List<String> tags;
  List<Poster> posters;

  TopicData(
      {required this.id,
      required this.title,
      required this.posters,
      required this.tags});

  factory TopicData.fromJson(Map<String, dynamic> json) {
    var posters = (json['posters'] as List).map((e) {
      return Poster.fromJson(e);
    }).toList();
    return TopicData(
        id: json['id'] as int,
        title: json['title'] as String,
        posters: posters,
        tags: (json['tags'] as List).map((e) {
          return e.toString();
        }).toList());
  }
}

class Poster {
  int user_id;
  String description;
  String? avatar;
  User? user;

  Poster({
    required this.user_id,
    required this.description,
    this.user,
    this.avatar,
  });

  factory Poster.fromJson(Map<String, dynamic> json) {
    return Poster(
      user_id: json['user_id'],
      description: json['description'],
    );
  }
}
